package com.kuaigou.cim.action.admin;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.cim.nio.session.CIMSession;
import com.farsunset.cim.nio.session.SessionManager;
import com.farsunset.ichat.cim.push.SystemMessagePusher;
import com.farsunset.ichat.common.util.ContextHolder;


@Controller
public class SessionAction {
	
	protected final Logger logger = Logger.getLogger(SessionAction.class);
	
	/**
	 * session 用户列表
	 * 
	 */
	@RequestMapping(value = "/admin/list.action")
	public String findByPage(ModelMap model) throws Exception{		
		SessionManager sessionManager= ContextHolder.getBean(SessionManager.class);
		Collection<CIMSession> sessions = sessionManager.getSessions();
		for (CIMSession cimSession : sessions) {
			logger.error(cimSession);
		}
		model.put("sessionList", sessions);		
		return "session/manage";
	}
	
	/**
	 * 下线
	 */
	@RequestMapping(value = "/admin/offline.action")
	public @ResponseBody Object offline(String account) throws IOException {  		
		  Map<String, Object> datamap = new HashMap<String, Object>();
		  Message msg = new Message();
		  msg.setMid(UUID.randomUUID().toString());
		  msg.setType(CIMConstant.MessageType.TYPE_999);//强行下线消息类型
		  msg.setReceiver(account);	
		  datamap.put("code", 200);	
//		  datamap.put("message", msg);	
		  logger.info("用户下线推送：" + msg.toString());
		  try{
			 //向客户端 发送消息
		     ContextHolder.getBean(SystemMessagePusher.class).pushMessageToUser(msg);
		  }catch(Exception e){			
				datamap.put("code", 500);
				e.printStackTrace();
		  }
		  return datamap;		 
	}

}
